//
//  YSChannelView.m
//  YSKitDemo
//
//  Created by MOLBASE on 2018/8/14.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSChannelView.h"
#import "YSChannelHeader.h"
#import "YSChannelItem.h"

// 菜单列数
static NSInteger kColumnNumber = 4;
// 横向和纵向的间距
static CGFloat kCellMarginX = 15.0f;
static CGFloat kCellMarginY = 10.0f;

@interface YSChannelView () <UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation YSChannelView {
    UICollectionView *_collectionView;
    // 被拖拽的item
    YSChannelItem *_dragingItem;
    // 正在拖拽的indexpath
    NSIndexPath *_dragingIndexPath;
    //目标位置
    NSIndexPath *_targetIndexPath;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self buildUI];
    }
    return self;
}

- (void)buildUI {
    self.backgroundColor = [UIColor whiteColor];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat cellWidth = (self.bounds.size.width - (kColumnNumber + 1) * kCellMarginX) / kColumnNumber;
    flowLayout.itemSize = CGSizeMake(cellWidth, cellWidth / 2);
    flowLayout.sectionInset = UIEdgeInsetsMake(kCellMarginY, kCellMarginX, kCellMarginY, kCellMarginX);
    flowLayout.minimumLineSpacing = kCellMarginY;
    flowLayout.minimumInteritemSpacing = kCellMarginX;
    flowLayout.headerReferenceSize = CGSizeMake(self.bounds.size.width, 40);

    _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[YSChannelItem class] forCellWithReuseIdentifier:NSStringFromClass([YSChannelItem class])];
    [_collectionView registerClass:[YSChannelHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([YSChannelHeader class])];
    [self addSubview:_collectionView];

    _dragingItem = [[YSChannelItem alloc] initWithFrame:CGRectMake(0, 0, cellWidth, cellWidth / 2)];
    _dragingItem.hidden = true;
    [_collectionView addSubview:_dragingItem];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressMethod:)];
    longPress.minimumPressDuration = 0.3f;
    [_collectionView addGestureRecognizer:longPress];
}

#pragma mark - events
- (void)longPressMethod:(UILongPressGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:_collectionView];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            [self dragBegin:point];
            break;
        case UIGestureRecognizerStateChanged:
            [self dragChanged:point];
            break;
        case UIGestureRecognizerStateEnded:
            [self dragEnd];
            break;
        default:
            break;
    }
}

// 拖拽开始，找到拖拽的item
- (void)dragBegin:(CGPoint)point {
    _dragingIndexPath = [self getDragingIndexPathWithPoint:point];
    if (!_dragingIndexPath) {
        return;
    }

    [_collectionView bringSubviewToFront:_dragingItem];
    YSChannelItem *item = (YSChannelItem *)[_collectionView cellForItemAtIndexPath:_dragingIndexPath];
    item.isMoving = YES;
    _dragingItem.hidden = false;
    _dragingItem.frame = item.frame;
    _dragingItem.title = item.title;
    [_dragingItem setTransform:CGAffineTransformMakeScale(1.1, 1.1)];
}

// 正在被拖拽
- (void)dragChanged:(CGPoint)point {
    if (!_dragingIndexPath) {
        return;
    }

    _dragingItem.center = point;
    _targetIndexPath = [self getTargetIndexPathWithPoint:point];
    // 交换位置 如果没有找到_targetIndexPath则不交换位置
    if (_dragingIndexPath && _targetIndexPath) {
        // 更新数据源
        [self rearrangeInUseTitles];
        // 更新item位置
        [_collectionView moveItemAtIndexPath:_dragingIndexPath toIndexPath:_targetIndexPath];
        _dragingIndexPath = _targetIndexPath;
    }
}

// 拖拽结束
- (void)dragEnd {
    if (!_dragingIndexPath) {
        return;
    }
    CGRect endFrame = [_collectionView cellForItemAtIndexPath:_dragingIndexPath].frame;
    [_dragingItem setTransform:CGAffineTransformMakeScale(1.0, 1.0)];
    [UIView animateWithDuration:0.3 animations:^{
        _dragingItem.frame = endFrame;
    } completion:^(BOOL finished) {
        _dragingItem.hidden = YES;
        YSChannelItem *item = (YSChannelItem *)[_collectionView cellForItemAtIndexPath:_dragingIndexPath];
        item.isMoving = NO;
    }];
}

// 获取被拖动IndexPath
- (NSIndexPath *)getDragingIndexPathWithPoint:(CGPoint)point {
    NSIndexPath *dragIndexPath = nil;
    if ([_collectionView numberOfItemsInSection:0] == 1) {
        return dragIndexPath;
    }

    for (NSIndexPath *indexPath in _collectionView.indexPathsForVisibleItems) {
        // 下半部分不需要排序
        if (indexPath.section > 0) {
            continue;
        }

        if (CGRectContainsPoint([_collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            if (indexPath.row != 0) {
                dragIndexPath = indexPath;
            }
            break;
        }
    }
    return dragIndexPath;
}

// 获取目标IndexPath
- (NSIndexPath*)getTargetIndexPathWithPoint:(CGPoint)point {
    NSIndexPath *targetIndexPath = nil;
    for (NSIndexPath *indexPath in _collectionView.indexPathsForVisibleItems) {
        // 如果是自己不需要排序
        if ([indexPath isEqual:_dragingIndexPath]) {continue;}
        // 第二组不需要排序
        if (indexPath.section > 0) {continue;}
        //在第一组中找出将被替换位置的Item
        if (CGRectContainsPoint([_collectionView cellForItemAtIndexPath:indexPath].frame, point)) {
            if (indexPath.row != 0) {
                targetIndexPath = indexPath;
            }
        }
    }
    return targetIndexPath;
}

// 拖拽排序后需要重新排序数据源
- (void)rearrangeInUseTitles {
    id obj = [_inUseTitles objectAtIndex:_dragingIndexPath.row];
    [_inUseTitles removeObject:obj];
    [_inUseTitles insertObject:obj atIndex:_targetIndexPath.row];
}

- (void)reloadData {
    [_collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return section == 0 ? _inUseTitles.count : _unUseTitles.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (![kind isEqualToString:UICollectionElementKindSectionHeader]) {
        return nil;
    }

    YSChannelHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([YSChannelHeader class]) forIndexPath:indexPath];
    if (indexPath.section == 0) {
        header.title    = @"已选频道";
        header.subTitle = @"按住拖拽调整排序";
    } else {
        header.title    = @"推荐频道";
        header.subTitle = @"";
    }
    return header;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YSChannelItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([YSChannelItem class]) forIndexPath:indexPath];
    item.title = indexPath.section == 0 ? _inUseTitles[indexPath.row] : _unUseTitles[indexPath.row];
    item.isFixed = indexPath.section == 0 && indexPath.row == 0;
    return item;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return;
        }

        id obj = [_inUseTitles objectAtIndex:indexPath.row];
        [_inUseTitles removeObject:obj];
        [_unUseTitles insertObject:obj atIndex:0];
        [_collectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    } else {
        id obj = [_unUseTitles objectAtIndex:indexPath.row];
        [_unUseTitles removeObject:obj];
        [_inUseTitles addObject:obj];
        [_collectionView moveItemAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForRow:_inUseTitles.count-1 inSection:0]];
    }
}

@end
